package com.config;

import com.listerner.ApiInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.converter.BufferedImageHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ApiInterceptor apiInterceptor;

    /**
     全局配置一次性解决每一个方法上都去加注解未免太麻烦了
     全局配置只需要在配置类中重写addCorsMappings方法
     表示本应用的所有方法都会去处理跨域请求，
     allowedMethods表示允许通过的请求数,
     allowedHeaders则表示允许的请求头。
     ，就不必在每个方法上单独配置跨域了
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*");
    }

    /**
     * 增加图片转换器
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new BufferedImageHttpMessageConverter());
    }

   @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 定义jwt拦截器的规则
        registry.addInterceptor(apiInterceptor).addPathPatterns("/api/**");
    }
}


